package com.djsearch.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.djsearch.R;
import com.djsearch.adapter.MovieAdapter;
import com.djsearch.bean.Movie;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.ui.GroupShopActivity.RequestParamStruct;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;



public class MovieActivity extends BaseActivity {

	Button back;
	MovieAdapter adapter;
	private ListView movieList;
	private int PAGE = 1;// 当前显示到第几页数据
	private List<Movie> nextPageMovieList;// 存放下一页请求的新数据
	private List<Movie> MovieList;
    private EditText searchEdit;
    private TextView renqiText, jiageText, dazeText;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.movie_layout);
		// 得到屏幕的分辨率
		getDisPlayMetrics();
		// 初始化主界面
		initView();
		// 初始化主界面相关点击事件
		initOnClick();
		// 初始化handler
		initHandler();
	}

	@Override
	void initHandler() {
		// TODO Auto-generated method stub

	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		
		MovieList=new ArrayList<Movie>();
		nextPageMovieList=new ArrayList<Movie>();
		back = (Button) findViewById(R.id.btnBack);
		movieList = (ListView) findViewById(R.id.movie_list);
		RequestParamStruct.queryByOrder = "";
		PAGE = 1;
		RequestParamStruct.page = 1;
		requestMovieData(initRequestMap());
		adapter = new MovieAdapter(MovieActivity.this, MovieList);
		movieList.setAdapter(adapter);
		searchEdit = (EditText)findViewById(R.id.init_name);
		
		renqiText = (TextView)findViewById(R.id.renqiText);
		jiageText = (TextView)findViewById(R.id.jiageText);
		dazeText = (TextView)findViewById(R.id.dazeText);
//		searchEdit.setInputType(InputType.TYPE_DATETIME_VARIATION_NORMAL);
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(searchEdit.getWindowToken(),0); 
		
	}

	@Override
	void initOnClick() {
		// TODO Auto-generated method stub
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(MovieActivity.this, MainActivity.class, 1);
			}
		});
		movieList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				
				Intent intent=new Intent(MovieActivity.this, MovieDetailsActivity.class);
				intent.putExtra("data", MovieList.get(arg2));
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
		
		renqiText.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				renqiText.setBackgroundResource(R.drawable.fentiaolan_top_seleted);
				jiageText.setBackgroundResource(R.drawable.fenlantiao_top);
				dazeText.setBackgroundResource(R.drawable.fenlantiao_top);
				RequestParamStruct.queryByOrder = "2";
				RequestParamStruct.page = 1;
				PAGE = 1;
				movieList.setVisibility(View.GONE);
				MovieList.clear();
				requestMovieData(initRequestMap());
			}
		});
		jiageText.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				jiageText.setBackgroundResource(R.drawable.fentiaolan_top_seleted);
				renqiText.setBackgroundResource(R.drawable.fenlantiao_top);
				dazeText.setBackgroundResource(R.drawable.fenlantiao_top);
				RequestParamStruct.queryByOrder = "3";
				RequestParamStruct.page = 1;
				PAGE = 1;
				movieList.setVisibility(View.GONE);
				MovieList.clear();
				requestMovieData(initRequestMap());
			}
		});
		dazeText.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dazeText.setBackgroundResource(R.drawable.fentiaolan_top_seleted);
				jiageText.setBackgroundResource(R.drawable.fenlantiao_top);
				renqiText.setBackgroundResource(R.drawable.fenlantiao_top);
				RequestParamStruct.queryByOrder = "4";
				RequestParamStruct.page = 1;
				PAGE = 1;
				movieList.setVisibility(View.GONE);
				MovieList.clear();
				requestMovieData(initRequestMap());
			}
		});
		
		movieList.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						if (!(progressBarPopuWindow != null && progressBarPopuWindow.isShowing())) {
					        RequestParamStruct.page = PAGE;
					        requestMovieData(initRequestMap());
						}
					}
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(MovieActivity.this, MainActivity.class, 1);
		}
		return false;
	}

	/**
	 * {"movieName":"无乐不作2D电影","price":"70.0",
	 * "shopUrl":"http:\/\/m.meituan.com\/shanghai\/deal\/4683465.html",
	 * "smallImage":"http:\/\/p1.meituan.net\/275.168\/deal\/__7785806__1411604.jpg",
	 * "longitude":"121.483657","latitude":"31.26124",
	 * "place":"虹口区四川北路1851号荣欣大厦703单元（近多伦路）",
	 * "bigImage":"http:\/\/p1.meituan.net\/275.168\/deal\/__7785806__1411604.jpg",
	 * "telephone":"021-66280073"}
	 */
	
	@Override
	void getDataToResolve(JSONResp responseJSON) {
		// TODO Auto-generated method stub
		try {
			Gson gson = new Gson();
			Type type = new TypeToken<List<Movie>>() {
			}.getType(); // 指定集合对象属性
			List<Movie> fromJson = gson.fromJson(
					responseJSON.getString("returnMessage"), type);
			nextPageMovieList.addAll(fromJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (nextPageMovieList.size() == 0) {
				// 当没有更多的数据了处理
			} else {
				MovieList.addAll(nextPageMovieList);
				nextPageMovieList.clear();
			}
			adapter.refreshData(MovieList);
		}
	}

	/**
	 * 请求服务器数据方法
	 */
	private void requestMovieData(Map<String, String> map) {
		IRequest request = new JSONReq("movie", map);

		HTTP.post(request, new AsyncHandler() {
			@Override
			public void onStart() {
				// showProgressBar(backBtn);
				showDialog("正在加载...");
			}

			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if (IResponse.Success == result) {
					++PAGE;
					getDataToResolve(response);
					Toast.makeText(MovieActivity.this, "成功" + PAGE, 5000)
							.show();
				} else if (IResponse.Fail == result) {
					// 返回数据失败
					getDataToResolve(response);
					Toast.makeText(MovieActivity.this, "失败", 5000).show();
				}
				missDialog();
				movieList.setVisibility(View.VISIBLE);
			}

			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
				missDialog();
				movieList.setVisibility(View.VISIBLE);
			}

		});
	}

	private static class RequestParamStruct{
		static String queryByName = "";//商品名称，为空时是请求所有团购商品
		static String queryByOrder = "2";//团购排序,,人气，价格，打折
		static String longitude = ""; //经度  getSharedPreferences("LOC", 0).getString("city", "北京")
		static String latitude = "";//纬度
		static int page = 1;//页码
		static String pageNum = "10";//一页显示的数据条数 
	}
	
	
	private Map<String, String> initRequestMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("queryByName", RequestParamStruct.queryByName);// 商品名称，为空时是请求所有团购商品
		map.put("queryByOrder", RequestParamStruct.queryByOrder);// 人气  价格  打折 2 3 4
		map.put("page", String.valueOf(RequestParamStruct.page));// 页码
		map.put("pageNum", RequestParamStruct.pageNum);// 一页显示的数据条数
		map.put("longitude", RequestParamStruct.longitude);// 经度
		map.put("latitude", RequestParamStruct.latitude);// 纬度
		return map;
	}
}
